package com.it.system.service.impl;

import com.github.pagehelper.PageHelper;
import com.it.system.domain.Employee;
import com.it.system.domain.Role;
import com.it.system.mapper.EmployeeMapper;
import com.it.system.query.EmployeeQuery;
import com.it.system.service.IEmployeeService;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
@Service
// 查询事务控制方式：设置只读 支持当前事务，如果没有当前事务，就以非事务方法执行。
@Transactional(readOnly = true,propagation = Propagation.SUPPORTS)
public class EmployeeServiceImpl implements IEmployeeService {
    @Autowired
    private EmployeeMapper employeeMapper;

    @Override
    @Transactional
    public void addEmployee(Employee employee) {
        employeeMapper.addEmployee(employee);
        if(employee.getRoles() != null && employee.getRoles().size() > 0){
            employeeMapper.addEmpAndRoles(employee);
        }
    }

    @Override
    @Transactional
    public void updateEmployee(Employee employee) {
        employeeMapper.updateEmployee(employee);
        employeeMapper.delEmpAndRoles(employee.getId());
        if(employee.getRoles().size() > 0){
            employeeMapper.addEmpAndRoles(employee);
        }
    }

    @Override
    @Transactional
    public void deteleById(Long id) {
        employeeMapper.deteleById(id);
        employeeMapper.delEmpAndRoles(id);
    }

    @Override
    public Employee findOne(Long id) {
        return employeeMapper.findOne(id);
    }

    @Override
    public List<Employee> findAll() {
        return employeeMapper.findAll();
    }

    @Override
    public List<Employee> queryPage(EmployeeQuery employeeQuery) {
        PageHelper.startPage(employeeQuery.getCurrentPage(), employeeQuery.getPageSize());
        List<Employee> employeeList = employeeMapper.queryPage(employeeQuery);
        for (Employee employee : employeeList) {
            List<Role> dbRoles = employeeMapper.findDbRoles(employee.getId());
            if (dbRoles.size() > 0&&dbRoles!=null) {
                employee.setDbRoles(dbRoles);
            }
        }
        return employeeList;
    }

    @Override
    @Transactional
    public void deleteEmployeeByIds(Long[] ids) {
        employeeMapper.deleteEmployeeByIds(ids);
        employeeMapper.delEmpAndRoles2(ids);
    }
}
